# some additional functions we can import
#
# if our application is the star attraction,
# then these are the supporting actors.

import os
import sys
import urllib
from google.appengine.ext.webapp import template
from util.sessions import Session
from core.game import Game


# render a page using the given template and return as a string
def render_page(tname = 'index.html', values = { }):
    templ = os.path.join(
          os.path.dirname(__file__),
          '../templates/' + tname)
    if not os.path.isfile(templ):
        return 'Error:  Template ' + tname + ' not found.'

    return template.render(templ, values)

# builds a route for a given room handler
# the third parameter is usually omitted when called directly, but is used by default_route
# to set route to "/"
def build_route(module_name, handler_name, special_route=''):
    import_name = 'rooms.' + module_name
    
    # allows us to import this module using name as string
    # need to use sys.modules to look up module (since nested module not returned directly by __import__)
    # see http://docs.python.org/library/functions.html#__import__ for more details
    __import__(import_name)
    this_module = sys.modules[import_name]
    
    # now need to get our hands on the specific handler in this module
    this_handler = getattr(this_module,handler_name)
    
    # the path corresponds to the module name with a "/" in front
    # unless we have a special route, in which case use that
    if special_route:
        this_path = special_route
    else:
        this_path = get_path(module_name)
    
    return (this_path,this_handler)

# add default route (the starting point of the game)
def default_route(module_name, handler_name):
    return build_route(module_name, handler_name, "/")

def build_form(form_name, form_handler):
    return ('/'+form_name, form_handler)

# store text as cutscene to be used in next room display
def set_cutscene(content):
    session = Session()    # find or create the session
    session['cutscene'] = content

# called when cutscene is going to be displayed
# if there is a cutscene return that and clear cutscene
# otherwise just return empty string
def play_cutscene():
    session = Session()    # find or create the session
    cutscene = session.get('cutscene','')
    if cutscene != '':
        session['cutscene'] = ''
    
    return cutscene

# get_game() returns game object
#
# we use the variable cur_game which is defined in 
# the namespace of this module (support.py) to store
# the game object.  this allows us to ensure that there is
# always at most one game object in play.  otherwise if
# multiple get_game() requests are made when processing a single
# request, changes made to one game object can overwrite
# those made in another.
#
# get_game first checks to see if there is already a game object
# stored in cur_game, in which case it returns that.  otherwise,
# retrieve game object from session.  if there is no game object
# stored yet, create one.  store game object in cur_game

cur_game = None     # note that this variable must be defined oustide get_game so it is in the module namespace

def get_game():
    
    global cur_game     # access module's cur_game variable
    
    session = Session()    # find or create the session

    # get game object if we don't have it
    if not cur_game:
        cur_game = session.get('game','')
        if not cur_game:
            cur_game = Game()
            session['game'] = cur_game
    
    return cur_game

# reset game by clearing session and also clearing cur_game variable
def reset_game():
    global cur_game
    cur_game = None
    
    session = Session()    # find or create the session
    
    cur_keys = session.session.keys()
            
    # delete all keys from session
    for key in cur_keys:
        session.delete_item(key)

# turn a string into a path by prefixing a "/" and escaping any special characters
def get_path(path_text):
    return "/" + urllib.quote(path_text)

# get room_id from name of the module in which this handler class
# was defined (since room id created
# using name of file in which this handler is found)
def get_room_id(handler):
    module_name = handler.__class__.__module__
    
    # we only want the unqualified module name
    path = module_name.split('.')
    
    return path[-1]
    